/**
 * @author 黄波
 * 创建日期：2011Sep 17, 2011
 * TODO// N/A
 */
package com.platform.user.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import net.sf.json.JSONObject;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.util.ServletContextAware;

import com.platform.common.bo.CommonBo;
import com.platform.constant.ResponseCode;
import com.platform.constant.SaveDir;
import com.platform.pojo.UserInfo;
import com.platform.user.bo.UserBo;

/**
 * 批量添加用户
 */
public class BatchAddUserAction extends UserSupport implements ServletContextAware{

	private File upload;
	//封装上传文件类型的属性
	private String uploadContentType;
	//封装上传文件名的属性
	private String uploadFileName;
	//如果是学生，则管理员在导入用户数据时，将选择班级
	private String classId;
	private UserInfo user;
	private String msg;
	private boolean success;
    private ServletContext context;
    public void setServletContext(ServletContext context) {   
        this.context = context;   
    }   
	public String getMsg() {
		return msg;
	}
	public void setMsg(String msg) {
		this.msg = msg;
	}
	public boolean isSuccess() {
		return success;
	}
	public void setSuccess(boolean success) {
		this.success = success;
	}
	public File getUpload() {
		return upload;
	}
	public void setUpload(File upload) {
		this.upload = upload;
	}
	public String getUploadContentType() {
		return uploadContentType;
	}
	public void setUploadContentType(String uploadContentType) {
		this.uploadContentType = uploadContentType;
	}
	public String getUploadFileName() {
		return uploadFileName;
	}
	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}
	public ServletContext getContext() {
		return context;
	}
	public void setContext(ServletContext context) {
		this.context = context;
	}
	public UserInfo getUser() {
		return user;
	}
	public void setUser(UserInfo user) {
		this.user = user;
	}
	private String generateFileName(String fileName) {   
        DateFormat format = new SimpleDateFormat("yyMMddHHmmss");   
        String formatDate = format.format(new Date());   
           
        int random = new Random().nextInt(10000);   
           
        int position = fileName.lastIndexOf(".");   
        String extension = fileName.substring(position);   
           
        return formatDate + random + extension;   
    }
	@Override
	public String execute() throws Exception {
		try {
			if(user.getGroupId() == null || user.getGroupId().equals("") || upload == null) {
				msg = ResponseCode.FAILURE_NO_DATA;
			} else {
				UserBo bo = UserBo.getInstance();
//			MultiPartRequest multipartRequest = ((MultiPartRequest)ServletActionContext.getRequest());
//			File[] files = multipartRequest.getFile("accountfile");
				String targetDirectory = context.getRealPath(SaveDir.USER_FILE);   
			    String targetFileName = uploadFileName;
//	        System.out.println(uploadContentType);
			    File target = new File(targetDirectory, targetFileName);
			    File dir = new File(target.getParent());
			    if(!dir.exists()) {
			    	dir.mkdirs();
			    }
			    if(!target.exists()) {
			    	target.createNewFile();
			    }
			    
			    FileOutputStream fos = new FileOutputStream(target);
			    FileInputStream fis = new FileInputStream(upload);  
			    byte[] buffer = new byte[1024];  
			    int len = 0;  
			    while((len = fis.read(buffer)) > 0){  
			        fos.write(buffer, 0, len);  
			    }
			    fos.flush();
			    if(fos != null) {
			    	fos.close();
			    }
			    if(fis != null) {
			    	fis.close();
			    }
			    
				Workbook book = Workbook.getWorkbook(target);  
			    Sheet se = book.getSheet(0);//得到第1个sheet(Excel通常会有3个Sheet)  
			    int rownum = se.getRows();   //得到总行数
			    List<UserInfo> users = new ArrayList<UserInfo>();
			    Date now = new Date();
			    for(int i = 1;i<rownum;i++) {
			    	UserInfo user = new UserInfo();
			    	user.setLoginName(se.getCell(0, i).getContents());	//默认用户名为学号或工号
			    	user.setRealName(se.getCell(1, i).getContents());	//用户真实姓名
			    	//用户系别
			    	if(se.getCell(2, i).getContents() != null) {
			    		Cell cell = se.getCell(2, i);
			    		if(cell != null && cell.getContents() != null && !cell.getContents().equals("")) {
			    			user.setDepartmentId(Integer.parseInt(cell.getContents()));
			    		}
			    	}
			    	//用户专业
			    	if(se.getCell(3, i).getContents() != null) {
			    		Cell cell = se.getCell(3, i);
			    		if(cell != null && cell.getContents() != null && !cell.getContents().equals("")) {
			    			user.setProfessionalId(Integer.parseInt(cell.getContents()));	
			    		}
			    	}
			    	//年级
			    	if(se.getCell(4, i).getContents() != null) {
			    		Cell cell = se.getCell(4, i);
			    		if(cell != null && cell.getContents() != null && !cell.getContents().equals("")) {
			    			user.setGradeId(Integer.parseInt(cell.getContents()));	
			    		}
			    	}
			    	//班级
			    	if(se.getCell(5, i).getContents() != null) {
			    		Cell cell = se.getCell(5, i);
			    		if(cell != null && cell.getContents() != null && !cell.getContents().equals("")) {
			    			user.setClassId(Integer.parseInt(cell.getContents()));
			    		}
			    	}
			    	//手机
			    	user.setMobile(se.getColumns() > 6 && se.getCell(6, i) != null ? se.getCell(6, i).getContents() : null);
			    	//邮箱
			    	user.setEmail(se.getColumns() > 6 && se.getCell(7, i) != null ? se.getCell(7, i).getContents() : null);
			    	//默认密码123456
			    	user.setLoginPasswd("123456");
			    	user.setGroupId(this.user.getGroupId());
			    	user.setRegTime(now);
			    	//默认批量上传的用户都经过审核了
			    	user.setIsAudit(1);
			    	user.setScore(100);	//注册赠送100积分
			    	user.setShareCount(0);
			    	user.setDownloadedCount(0);
			    	user.setDownloadCount(0);
			    	user.setUserScore(0);
//			    	user.setClassId(Integer.parseInt(classId));
			    	users.add(user);
			    }
			    for(UserInfo user : users) {
			    	if(!bo.addUser(user)) {
			    		msg = ResponseCode.FAILURE_MUTI_USER;
			    		continue;//添加不成功则继续
			    	}
			    	CommonBo commonBo = CommonBo.getInstance();
			    	if(user.getClassId() != null) {
			    		commonBo.updateClassNum(user.getClassId().toString(), 1 );
			    	}
			    }
			    if(msg == null) {
			    	msg = ResponseCode.SUCCESS_BATCH_ADD;
			    }
			}
		} catch (Exception e) {
			e.printStackTrace();
			msg = "错误，请审核文件后重试！";
		}

		success = true;
		HashMap map = new HashMap();
		map.put("msg", msg);
		map.put("success", success);
		JSONObject json = JSONObject.fromObject(map);
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("text/html;charset=UTF-8");
		response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		out.println(json);
		out.flush();
		out.close();
		return null;
	}
	public String getClassId() {
		return classId;
	}
	public void setClassId(String classId) {
		this.classId = classId;
	}
	
}
